package com.io.nio;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author shichenguang
 * @desciption 描述
 * @date 2020-05-18 14:27
 */
public class NioDemo {
    public static void main(String[] args) {

    }



    /**
     * @description  nio基本使用
     * @author shichenguang
     * @date 2020/5/18 14:35
     */
    @Test
    public  void  readAndWrite(){
        String tmp  = "123134";
        //指定缓冲区大小
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //写入数据
        byteBuffer.put(tmp.getBytes());
        //切换读取数据模式（index至0)
        byteBuffer.flip();
        byte[] dst = new byte[byteBuffer.limit()];
        //使用get方法获取数据
        byteBuffer.get(dst);
        System.out.println(new String(dst,0,dst.length));
        System.out.println("test姓名2");
    }

    /**
     * @description 简单示例使用通道和缓冲区复制文件
     * @author shichenguang
     * @date 2020/5/18 14:49
     */
    @Test
    public void channelTest() throws IOException {
        FileInputStream fis = new FileInputStream("123.doc");
        FileOutputStream fos = new FileOutputStream("123.doc");
        //获取通道
        FileChannel inChannel = fis.getChannel();
        FileChannel outChannel = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //将通道的数据存入缓冲区

        while (inChannel.read(buffer) != -1){     //从该通道读取到给定缓冲区的字节序列
            //缓冲区切换模式
            buffer.flip();
            outChannel.write(buffer);            //从给定的缓冲区向该通道写入一个字节序列
            buffer.clear();
        }

        outChannel.close();
        inChannel.close();
        fis.close();
        fos.close();
    }

}
